$(function () {
    init_followTab();
    init_time();
    init_selectUsers();
    indexFollowUserList();
    index_selectUsers();
    init_indexList();
    selectTelUserList();
    init_telUsers();
    init_telTab();
    init_teltime();
    $("body").on('click','[data-stopPropagation]',function (e) {e.stopPropagation();});
});

/**初始化时间选择**/
function init_time(){
    $("#select_time span").html(moment().subtract("days",29).format("YYYY-MM-DD")+" - "+moment().format("YYYY-MM-DD"));
    $('#select_time').daterangepicker({
        timePicker: true, //显示时间
        timePicker24Hour: true, //时间制
        timePickerSeconds: true, //时间显示到秒
        startDate: moment().hours(0).minutes(0).seconds(0), //设置开始日期
        endDate: moment(new Date()), //设置结束器日期
        maxDate: moment(new Date()), //设置最大日期
        "opens": "center",
        ranges: {
            '今天': [moment(), moment()],'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '上周': [moment().subtract(6, 'days'), moment()],
            '前30天': [moment().subtract(29, 'days'), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        showWeekNumbers: true,
        locale: {
            format: "YYYY-MM-DD HH:mm:ss", //设置显示格式
            applyLabel: '确定', //确定按钮文本
            cancelLabel: '取消', //取消按钮文本
            customRangeLabel: '自定义',
            daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                '七月', '八月', '九月', '十月', '十一月', '十二月'
            ],
            firstDay: 1
        },
    }).on('apply.daterangepicker', function(ev, picker) {
        var starttime = picker.startDate.format('YYYY-MM-DD');
        var endtime = picker.endDate.format('YYYY-MM-DD');
        $("#select_time span").html(starttime+" - "+endtime);
        $("#starttime").val(starttime);
        $("#endtime").val(endtime);
        $JuXue.refreshTable("followTab");
    });
}


function init_teltime() {
    $("#telselect_time span").html(moment().subtract("days",29).format("YYYY-MM-DD")+" - "+moment().format("YYYY-MM-DD"));
    $('#telselect_time').daterangepicker({
        timePicker: true, //显示时间
        timePicker24Hour: true, //时间制
        timePickerSeconds: true, //时间显示到秒
        startDate: moment().hours(0).minutes(0).seconds(0), //设置开始日期
        endDate: moment(new Date()), //设置结束器日期
        maxDate: moment(new Date()), //设置最大日期
        "opens": "center",
        ranges: {
            '今天': [moment(), moment()],'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '上周': [moment().subtract(6, 'days'), moment()],
            '前30天': [moment().subtract(29, 'days'), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        showWeekNumbers: true,
        locale: {
            format: "YYYY-MM-DD HH:mm:ss", //设置显示格式
            applyLabel: '确定', //确定按钮文本
            cancelLabel: '取消', //取消按钮文本
            customRangeLabel: '自定义',
            daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                '七月', '八月', '九月', '十月', '十一月', '十二月'
            ],
            firstDay: 1
        },
    }).on('apply.daterangepicker', function(ev, picker) {
        var starttime = picker.startDate.format('YYYY-MM-DD');
        var endtime = picker.endDate.format('YYYY-MM-DD');
        $("#telselect_time span").html(starttime+" - "+endtime);
        $("#telstarttime").val(starttime);
        $("#telendtime").val(endtime);
        $JuXue.refreshTable("telfollowTab");
    });
}

/**初始化列表**/
function init_followTab() {
    var settings = {
        url: ctx + "cusDynamic/selectFollowData",
        queryParams: function(params) {
            return {
                pageSize : params.limit,
                pageNum  : params.offset / params.limit + 1,
                dyCreator   : $("#gerenfollow").val(),//选择人员
                starttime: $("#starttime").val(), //开始时间
                endtime  : $("#endtime").val(),//结束时间
                dyCusName:$("#searchValue").val()//客户名称
            };
        },
        columns: [ {
            field: 'dyCreattime',
            title: '联系时间'
        },{
            field: 'dyDisName',
            title: '客户名称',
            formatter:function (value, row, index) {
                return "<a href='javascript:;' class='btn btn-link btn-xs' cusid='"+row.dyCusUuid+"' typeid='"+row.dySourceType+"' onclick='selectCusDetail(this)'>"+value+"</a>";
            }
        },{
            field: 'dyFollowContent',
            title: '跟进记录'
        },{
            field: 'dyCreatorName',
            class: 'text-center',
            title: '跟进人',
        }],
    };
    $JuXue.initTable('followTab', settings);
}

/**查客户详情*/
function selectCusDetail(btn){
    var type = $(btn).attr("typeid");
    var ids = $(btn).attr("cusid");
    $("#customer_uuid").val(ids);
    $("#customer_ids").val(ids);
    $("#customer_type").val(type);
    $.post(ctx+"myCustomer/loadCustomerDetail",{type:type},function (r) {
        $("#myCustomer-modal").empty().append(r).modal('show');
    });
}

/**选择员工**/
function selectFollowUserList(){
    $('#selectFollowUsers').removeClass('open');
    var usersArray = new Array();
    //说明选择了人员
    $("#followSelctUsers").find("div").each(function () {
        var users = $(this).attr("data-id");
        usersArray.push(users);
    });
    $("#gerenfollow").val(usersArray.join(","));
    $JuXue.refreshTable("followTab");
}

/**初始化选择人员**/
function init_selectUsers(){
    $.post(ctx+"dept/getUserAndDeptByTreeWhisRole",{},function (r) {
        var array  = r.msg;
        $("#select_follow_user").jstree({
            "core": {
                "multiple": true,//单选
                "data":array,
                "icon":false,
                "themes":{
                    "icons":false
                }
            },
            "checkbox" : {
                "keep_selected_style" : false
            },
            "plugins" : [ "wholerow", "checkbox" ]
        });
        // 获得点击节点的id
        $('#select_follow_user').on("changed.jstree", function (e, data) {
            var nodeid = data.node.id;
            var text = data.node.text;
            var action = data.action;;
            if (action == "deselect_node") {
                $("#followSelctUsers").find("div").each(function () {
                    var data_id = $(this).attr("data-id");
                    if (data_id == nodeid) $(this).remove();
                });
            }else{
                /**判断是不是超过 3个 超过3个则不能继续追加**/
                var divlength = $("#followSelctUsers").find("div");
                if(divlength.length >= 3){
                    $JuXue.n_danger("选择查询类型不能超过3个");
                    $("#select_follow_user").jstree("deselect_node",nodeid);
                    return;
                }else{
                    if(divlength.length >0){
                        var ble = false;
                        $("#followSelctUsers").find("div").each(function () {
                            var data_id = $(this).attr("data-id");
                            if (data_id == nodeid){ble = true;}
                        });
                        if(!ble){
                            var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";
                            $("#followSelctUsers").append(label);
                        }
                    }else{
                        var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";
                        $("#followSelctUsers").append(label);
                    }
                }
            }
        });
    });
}


/**选择员工**/
function indexFollowUserList(){
    $('#indexFollowUsers').removeClass('open');
    var usersArray = new Array();
    //说明选择了人员
    $("#indexSelctUsers").find("div").each(function () {
        var users = $(this).attr("data-id");
        usersArray.push(users);
    });
    $("#indexfollow").val(usersArray.join(","));
    init_indexList();
}

/**初始化选择人员**/
function index_selectUsers(){
    $.post(ctx+"dept/getUserAndDeptByTreeWhisRole",{},function (r) {
        var array  = r.msg;
        $("#index_follow_user").jstree({
            "core": {
                "multiple": true,//单选
                "data":array,
                "icon":false,
                "themes":{
                    "icons":false
                }
            },
            "checkbox" : {
                "keep_selected_style" : false
            },
            "plugins" : [ "wholerow", "checkbox" ]
        });
        // 获得点击节点的id
        $('#index_follow_user').on("changed.jstree", function (e, data) {
            var nodeid = data.node.id;
            var text = data.node.text;
            var action = data.action;;
            if (action == "deselect_node") {
                $("#indexSelctUsers").find("div").each(function () {
                    var data_id = $(this).attr("data-id");
                    if (data_id == nodeid) $(this).remove();
                });
            }else{
                /**判断是不是超过 3个 超过3个则不能继续追加**/
                var divlength = $("#indexSelctUsers").find("div");
                if(divlength.length >= 3){
                    $JuXue.n_danger("选择查询类型不能超过3个");
                    $("#index_follow_user").jstree("deselect_node",nodeid);
                    return;
                }else{
                    if(divlength.length >0){
                        var ble = false;
                        $("#indexSelctUsers").find("div").each(function () {
                            var data_id = $(this).attr("data-id");
                            if (data_id == nodeid){ble = true;}
                        });
                        if(!ble){
                            var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";
                            $("#indexSelctUsers").append(label);
                        }
                    }else{
                        var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";
                        $("#indexSelctUsers").append(label);
                    }
                }
            }
        });
    });
}

//初始化今日沟通记录
function init_indexList() {
    var dyCreator = $("#indexfollow").val();//选择人员
    $.post(ctx+"cusDynamic/getFollowListByType",{dyCreator:dyCreator},function (r) {
        if(r.code===0){
            var data = r.data;
            var allcout = data.length;
            var cuscout = 0;
            var telcout = 0;
            $("#noneList").empty();
            $.each(data,function (index,val) {
                var type = val.dyType;
                var content = val.dyContent;
                var folowContent = val.dyFollowContent;
                var times = val.dyCreattime;
                var time = '今天 '+times.substring(10,16);
                var creator = val.dyCreatorName;
                var name = val.dyDisName;
                if(name==null){
                    name='--';
                }
                if(type==='9'){
                    var body = '<div class="row col-md-12 col-sm-12 col-xs-12 box-shadow-5 m-0 m-t-10 height-80" style="width: 98%;margin-left: 5px !important;margin-right: -10px;">' +
                           '        <div class="col-md-1 col-sm-1 col-xs-2 pull-left"><svg style="margin-left:-15px" width="5em" height="5em" viewBox="0 0 16 16" class="bi bi-clipboard-check p-t-15" fill="currentColor" xmlns="http://www.w3.org/2000/svg">\n' +
                           '            <path fill-rule="evenodd" d="M4 1.5H3a2 2 0 0 0-2 2V14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V3.5a2 2 0 0 0-2-2h-1v1h1a1 1 0 0 1 1 1V14a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V3.5a1 1 0 0 1 1-1h1v-1z"/>\n' +
                           '            <path fill-rule="evenodd" d="M9.5 1h-3a.5.5 0 0 0-.5.5v1a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-1a.5.5 0 0 0-.5-.5zm-3-1A1.5 1.5 0 0 0 5 1.5v1A1.5 1.5 0 0 0 6.5 4h3A1.5 1.5 0 0 0 11 2.5v-1A1.5 1.5 0 0 0 9.5 0h-3zm4.354 7.146a.5.5 0 0 1 0 .708l-3 3a.5.5 0 0 1-.708 0l-1.5-1.5a.5.5 0 1 1 .708-.708L7.5 9.793l2.646-2.647a.5.5 0 0 1 .708 0z"/>\n' +
                           '            </svg></div>'+
                           '        <div class="col-md-9 col-sm-9 col-xs-9 pull-left m-t-5"><div class="pull-left"><h5 class="pull-left">'+creator+content+'  <b class="text-info">'+name+'</b> </h5></div><br/><br/>'+
                           '        <div class="pull-left" style="overflow-y: auto;"><h5 class="text-left">跟进内容： '+folowContent+'</h5></div></div>'+
                           '        <div class="col-md-2 col-sm-2 col-xs-2 pull-right"><h5 style="position: absolute;height:80px;left:50%;top:50%;margin-left:-20px;margin-top:35px;">'+time+'</h5></div>'+
                           '    </div>';
                    $("#noneList").append(body);
                    cuscout++;
                }else{
                    var url = val.dyRecord.mPath;
                    if(url!=='isnull'){

                        body = '<div class="row col-md-12 col-sm-12 col-xs-12 box-shadow-5 m-0 m-t-10 height-80" style="width: 98%;margin-left: 5px !important;margin-right: -10px;">' +
                            '        <div class="col-md-1 col-sm-1 col-xs-2 pull-left"><svg style="margin-left:-15px;" width="3em" height="3em" viewBox="0 0 16 16" class="bi bi-telephone-fill m-t-15" fill="currentColor" xmlns="http://www.w3.org/2000/svg">\n' +
                            '           <path fill-rule="evenodd" d="M2.267.98a1.636 1.636 0 0 1 2.448.152l1.681 2.162c.309.396.418.913.296 1.4l-.513 2.053a.636.636 0 0 0 .167.604L8.65 9.654a.636.636 0 0 0 .604.167l2.052-.513a1.636 1.636 0 0 1 1.401.296l2.162 1.681c.777.604.849 1.753.153 2.448l-.97.97c-.693.693-1.73.998-2.697.658a17.47 17.47 0 0 1-6.571-4.144A17.47 17.47 0 0 1 .639 4.646c-.34-.967-.035-2.004.658-2.698l.97-.969z"/>\n' +
                            '            </svg></div>'+
                            '        <div class="col-md-9 col-sm-9 col-xs-9 pull-left m-t-7"><div class="pull-left"><h5 class="pull-left">'+creator+'（手机呼出）<b class="text-info">'+name+'</b> </h5></div><br/><br/>'+
                            '        <div class="pull-left" style="overflow-y: auto;"><h5 class="text-left">通话时长： <audio class="height-15 width-200" src="'+url+'"  controls="controls" controlsList="nodownload" οncοntextmenu="return false" type="audio/wav"></audio></h5></div></div>'+
                            '        <div class="col-md-2 col-sm-2 col-xs-2 pull-right"><h5 style="position: absolute;height:80px;left:50%;top:50%;margin-left:-20px;margin-top:35px;">'+time+'</h5></div>'+
                            '    </div>';

                        $("#noneList").append(body);
                        telcout++;
                    }
                }
            });
            $("#allCount").text(allcout);
            $("#telCount").text(telcout);
            $("#cusCount").text(cuscout);
        }
    })
}


/**选择员工**/
function selectTelUserList(){
    $('#telFollowUsers').removeClass('open');
    var usersArray = new Array();
    //说明选择了人员
    $("#telSelctUsers").find("div").each(function () {
        var users = $(this).attr("data-id");
        usersArray.push(users);
    });
    $("#telfollow").val(usersArray.join(","));
    $JuXue.refreshTable("telfollowTab");
}

/**初始化选择人员**/
function init_telUsers(){
    $.post(ctx+"dept/getUserAndDeptByTreeWhisRole",{},function (r) {
        var array  = r.msg;
        $("#tel_follow_user").jstree({
            "core": {
                "multiple": true,//单选
                "data":array,
                "icon":false,
                "themes":{
                    "icons":false
                }
            },
            "checkbox" : {
                "keep_selected_style" : false
            },
            "plugins" : [ "wholerow", "checkbox" ]
        });
        // 获得点击节点的id
        $('#tel_follow_user').on("changed.jstree", function (e, data) {
            var nodeid = data.node.id;
            var text = data.node.text;
            var action = data.action;;
            if (action == "deselect_node") {
                $("#telSelctUsers").find("div").each(function () {
                    var data_id = $(this).attr("data-id");
                    if (data_id == nodeid) $(this).remove();
                });
            }else{
                /**判断是不是超过 3个 超过3个则不能继续追加**/
                var divlength = $("#telSelctUsers").find("div");
                if(divlength.length >= 3){
                    $JuXue.n_danger("选择查询部门不能超过3个");
                    $("#tel_follow_user").jstree("deselect_node",nodeid);
                    return;
                }else{
                    if(divlength.length >0){
                        var ble = false;
                        $("#telSelctUsers").find("div").each(function () {
                            var data_id = $(this).attr("data-id");
                            if (data_id == nodeid){ble = true;}
                        });
                        if(!ble){
                            var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";
                            $("#telSelctUsers").append(label);
                        }
                    }else{
                        var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";
                        $("#telSelctUsers").append(label);
                    }
                }
            }
        });
    });
}

function init_telTab() {
    var settings = {
        url: ctx + "mrecordPc/getPhoneCallList",
        queryParams: function(params) {
            return {
                pageSize   : params.limit,
                pageNum    : params.offset / params.limit + 1,
                mUserid    : $("#telfollow").val(),//选择人员
                beforeTime : $("#telstarttime").val(), //开始时间
                afterTime  : $("#telendtime").val(),//结束时间
                searchValue:$("#telsearchValue").val(),//客户名称
                mType      :$("#callType").val(),
                mStatus    :$("#callStatus").val()
            };
        },
        columns: [ {
            field: 'mCusName',
            title: '客户名称',
            formatter:function (value, row, index) {
                return value;
            }
        },{
            field: 'mCusMobile',
            title: '电话号码'
        },{
            field: 'mType',
            title: '通话方式',
            formatter:function (value, row, index) {
                if(value==='1'){
                    return '呼出';
                }else if(value==='2'){
                    return '呼入';
                }
            }
        },{
            field: 'mUserName',
            title: '拨打人',
        },{
            field: 'creatTime',
            title: '拨打时间',
        },{
            field: 'mPath',
            title: '录音文件',
            formatter:function (value, row, index) {
                return '<audio class="height-15 width-200" src="'+value+'"  controls="controls" controlsList="nodownload" οncοntextmenu="return false" type="audio/wav"></audio>';
            }
        }],
    };
    $JuXue.initTable('telfollowTab', settings);
}

function selectCallType(btn) {

    $("#callTypeDiv").find("button").each(function () {$(this).removeClass("btn-primary");});
    $(btn).addClass("btn-primary");

    var data = $(btn).attr('data-click');
    $("#callType").val(data);
    $JuXue.refreshTable("telfollowTab");
}

function selectStatus(btn) {
    $("#callStatusDiv").find("button").each(function () {$(this).removeClass("btn-primary");});
    $(btn).addClass("btn-primary");

    var data = $(btn).attr('data-click');
    $("#callStatus").val(data);
    $JuXue.refreshTable("telfollowTab");
}